var express = require('express')
var router = express.Router()
var wechat = require('wechat')
var wechat_card = require('../controller/cardSign.js')
var Cwechat = require('../controller/wechat.js')
var Cpromotion = require('../controller/wechat_promotion.js')
var wechatmodel = require('../model/wechat.js')
var moment = require('moment')
var ticket = require('./ticket.js')
var paySign = require('./paySign.js')
var OAuth = require('wechat-oauth')
var fs = require('fs')
var async = require('async')
var voice = require('../model/voice.js')
var request = require('request')
var Curd = require('../model/curd.js')
var path = require('path')
var config = require('../config.js').wechat
var domainName = require('../config.js').domainName
var utils = require('../utils/utils.js')

//获取微信活动的数据
router.get('/promotion/find/:wmpname/:promotion_name', function (req, res) {
    var wmpname = req.params.wmpname
    var promotion_name = req.params.promotion_name
    var openid = req.query.openid
    var condition = {
        wmpname: wmpname,
        promotion_name: promotion_name,
        openid: openid
    }
    Cpromotion.find(condition, {}, function (err, result) {
        if (err) console.log(err)
        res.json(result)
    })
})
//更新微信活动的数据
router.get('/promotion/update/:wmpname/:promotion_name', function (req, res) {
    var wmpname = req.params.wmpname
    var playTime, last, sharedTime,Msg
    var promotion_name = req.params.promotion_name
    var openid = req.query.openid
    var update_type = req.query.update_type
    var createDate = moment().format('YYYY-MM-DD HH:mm:ss')
    var condition = {
        wmpname: wmpname,
        promotion_name: promotion_name,
        openid: openid,
    }


    Cpromotion.find(condition, {}, function (err, result) {
        if (err) {
            cb(new Error(err))
        }
        if (result.length > 0) {
            playTime = result[0].playTime
            last = result[0].createDate
            sharedTime = result[0].sharedTime

            //先判断是不是一天内
            if (moment(last, 'YYYY-MM-DD').toNow(true).indexOf('day' || 'days') === -1) {
                if (playTime > 0 && update_type === 'play') {
                    playTime--
                }
                if (update_type === 'share') {
                    if (sharedTime !== 2) {
                        playTime++
                        sharedTime++
                    } else {
                        Msg = '超出分享限制'
                    }
                }
            } else {
                playTime = 1
                sharedTime = 0
            }
            var update = {
                playTime: playTime,
                sharedTime: sharedTime,
                createDate: createDate
            }
            Cpromotion.update(condition, update, {}, function (err) {
                if (err) {
                    res.json({message:err})
                } else {
                    res.json({message:Msg})
                }

            })
        } else {
            var data = {
                createDate: createDate,
                wmpname: wmpname,
                promotion_name: promotion_name,
                openid: openid
            }
            Cpromotion.save(data, function (err) {
                if (err) {
                    console.log(err)
                } else {
                    res.sendStatus(200)
                }
            })

        }
    })

})

//处理微信的语音
router.post('/wechat/voice/save', function (req, res) {
    console.log('voice save')
    var user = req.body
    var voicepath = __dirname + "/../public/voice/wmpaudio/"
    if (!fs.existsSync(voicepath)) {
        fs.mkdirSync(voicepath)
    }
    async.waterfall([
        function (cb) {
            ticket.gettoken(appid, secret, function (token) {
                cb(null, token)
            })
        },
        function (tk, cb) {
            //从微信服务器中根据serverid下载微信语音到指定的路径下
            var _url = 'https://api.weixin.qq.com/cgi-bin/media/get?access_token=' + tk + '&media_id=' + user.serverId
            user.path = './audio/' + user.serverId + '.mp3'
            user.vote = 0
            request.get(_url).on('err', function (err) {
                res.send(500, {message: err})
            }).pipe(fs.createWriteStream(voicepath + user.openid + ".mp3"))
            voice.update(user, function (err) {
                if (err) {
                    cb(new Error(err))
                } else {
                    cb(null)
                }
            })
        },
    ], function (err, result) {
        if (err) {
            console.log(err)
        } else {
            //do st.
            res.sendStatus(200)
        }
    })


})
router.get('/getWechatCard/:wmpname', function (req, res) {
    var wmpname = req.params.wmpname
    var openid = req.query.openid
    var card_id = req.query.card_id
    async.waterfall([
        function (cb) {
            Cwechat.getCardTiket(req, wmpname, function (err, result) {
                if (err) cb(new Error(err))
                cb(null, result.ticket)
            })
        },
        function (ticket, cb) {
            var ret = wechat_card(ticket, openid, card_id)
            cb(null, ret)
        }
    ], function (err, result) {
        if (err) console.log(err)
        res.json(result)
    })
})
//微信登陆
router.get('/login/:wmpname/:appname', function (req, res, next) {
    console.log('微信登录')
    var wmpname = req.params.wmpname
    var appname = req.params.appname
    var isLogin = req.query.isLogin
    var access_token_path = ""
    var datapath = path.resolve(__dirname, "../data/")
    if (isLogin && !req.session.code) {
        var appid = config[wmpname].appid
        var secret = config[wmpname].secret
        var client = new OAuth(appid, secret, function (openid, callback) {
            // 传入一个根据openid获取对应的全局token的方法
            // 在getUser时会通过该方法来获取token
            fs.readFile(access_token_path, 'utf8', function (err, txt) {
                if (err) {
                    return callback(err)
                }
                callback(null, JSON.parse(txt))
            })

        }, function (openid, token, callback) {
            access_token_path = datapath + '/' + wmpname + '_' + openid + ':auth_access_token.txt'
            if (fs.existsSync(access_token_path)) {
                fs.unlink(access_token_path)
            }
            //在登陆时保存token
            if (!fs.existsSync(datapath)) {
                fs.mkdir(datapath)
            }
            fs.writeFile(access_token_path, JSON.stringify(token), function (err) {
                if (err) console.log(err)
                callback(null)
            })

        })
        wechatFuncs = wechatmodel.config(wmpname + "_" + appname)
        var url = client.getAuthorizeURL("http://" + domainName + "/wechat_new/login/" + wmpname + "/" + appname + "?isLogin=true", 'mystate', 'snsapi_userinfo')
        var code = req.query.code
        if (code == undefined) {
            res.redirect(url)
        } else {
            async.waterfall([
                function (cb) {
                    client.getAccessToken(code, function (err, access_token) {
                        if (err) {
                            cb(new Error(err))
                        } else {
                            cb(null, access_token.data.openid)
                        }
                    })
                },
                function (openid, cb) {
                    Cwechat.getGeneralToken(req, wmpname, function (err, result) {
                        if (err) cb(new Error(err))
                        result.openid = openid
                        cb(null, result)
                    })
                },
                function (result, cb) {
                    Cwechat.getUser(result, function (err, user) {
                        if (err) cb(new Error(err))
                        cb(null, user)
                    })
                },
            ], function (err, result) {
                if (err) {
                    console.log(err)
                } else {
                    req.session.code = code
                    res.cookie("YSHUXN", {user: result}, {path: "/"})
                    res.redirect("/" + wmpname + "_" + appname)
                }
            })
        }
    } else {
        res.redirect("/" + wmpname + "_" + appname)
    }
})
// router.get("/:wmpname/getUser", function (req, res, next) {
//     var app = req.query.app
//     wechatFuncs = wechatmodel.config(app)
//     var openid = req.query.openid
//     wechatFuncs.findByid(openid, function (err, result) {
//         if (err) {
//             res.send(err)
//         } else {
//             res.send(result)
//         }
//     })
// })
//获取pay配置信息
router.get('/wechat/getpayconf', function (req, res, next) {
    var appid = config.zhixun.appid
    var paykey = config.zhixun.paykey
    var ret = new paySign(appid, paykey).getSign()
    res.send(ret)
})

//公众平台接入
router.get('/sign/:wmpname', function (req, res, next) {
    var wmpname = req.params.wmpname
    wechat(config[wmpname])
})


//公众平台开发
router.post('sign/:wmpname', wechat(config.zhixun, function (req, res, next) {
    // 微信输入信息都在req.weixin上
    var message = req.weixin
    console.log(message)
    if (message.FromUserName === 'diaosi') {
        // 回复屌丝(普通回复)
        res.reply('hehe')
    } else if (message.FromUserName === 'text') {
        //你也可以这样回复text类型的信息
        res.reply({
            content: 'text object',
            type: 'text'
        })
    } else if (message.FromUserName === 'hehe') {
        // 回复一段音乐
        res.reply({
            type: "music",
            content: {
                title: "来段音乐吧",
                description: "一无所有",
                musicUrl: "http://mp3.com/xx.mp3",
                hqMusicUrl: "http://mp3.com/xx.mp3",
                thumbMediaId: "thisThumbMediaId"
            }
        })
    } else {
        // 回复高富帅(图文回复)
        res.reply([{
            title: '你来我家接我吧',
            description: '这是女神与高富帅之间的对话',
            picurl: 'http://nodeapi.cloudfoundry.com/qrcode.jpg',
            url: 'http://nodeapi.cloudfoundry.com/'
        }])
    }
}))

router.get('/wechat/share', function (req, res, next) {
    var appname = req.query.appname
    var isLogin = req.query.isLogin
    var share = req.query.share
    var record = {}
    record.appname = appname
    record.isLogin = isLogin
    var visitor = new Curd()(require('../model/visitor.js'))
    visitor.save(record, function (err) {
        if (err) {
            res.send(500, {err: message})
        } else {
            res.sendStatus(200)
        }
    })
})
router.get('/wechat/getvisitor', function (req, res, next) {
    var appname = req.query.appname
    var visitor = new Curd()(require('../model/visitor.js'))
    async.waterfall([
        function (cb) {
            visitor.find({appname: appname}, function (err, result) {
                if (err) {
                    res.send(500, {message: err})
                } else {
                    cb(null, result)
                }
            })
        },
        function (result, cb) {
            var visitors = result.length
            k = 0
            for (var i = 0; i < visitors; i++) {
                if (result[i].share) {
                    k++
                }
            }
            cb(null, {visitors: visitors, shared: k})
        },
    ], function (err, result) {
        if (err) {
            console.log(err)
        } else {
            res.send(result)
        }
    })

})

//jssdk校验
var that = this
router.get('/jssdk/:wmpname', function (req, res, next) {
    console.log('进入jssdk')
    var wmpname = req.params.wmpname
    var appid = config[wmpname].appid
    var secret = config[wmpname].secret
    var signurl = req.query.url
    var signature = require('./signature.js')
    var apiTicket
    var ret = null

    async.waterfall([
        function (cb) {
            Cwechat.getGeneralToken(req, wmpname, function (err, result) {
                if (err) cb(new Error(err))
                cb(null, result)
            })
        },
        function (tob, cb) {
            ticket.getticket(tob.access_token, function (_ticket) {
                apiTicket = _ticket
                cb(null)
            })
        }
    ], function (err, result) {
        if (err) console.log(err)
        ret = new signature(apiTicket, appid, signurl)
        res.send(ret)
    })

})

module.exports = router